package org.example.dao;

import org.junit.Before;
import org.junit.Test;
import org.junit.After;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

import static org.example.Main.textUtils;
import static org.junit.Assert.*;

public class WordGraphTestHeiHe {

    private WordGraph wordGraph;
    private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
    private final PrintStream originalOut = System.out;

    @Before
    public void setUp() {
        String text = textUtils.processTextFile("src/main/java/org/example/input_txt/test.txt");
        wordGraph = new WordGraph(text);
        System.setOut(new PrintStream(outContent));
    }

    @After
    public void restoreStreams() {
        System.setOut(originalOut);
    }

    @Test
    public void testPathExistsSingle() {
        wordGraph.calcShortestPath("explore", "worlds","one_to_one");
        String expected = "Directory successfully created!\nAll shortest paths between explore and worlds:\nPath:\n - explore -> strange\n - strange -> new\n - new -> worlds\nPath length: 3.0\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    @Test
    public void testPathExistsMultiple() {
        wordGraph.calcShortestPath("to", "life","one_to_one");
        String expected = "Directory successfully created!\nAll shortest paths between to and life:\nPath:\n - to -> explore\n - explore -> strange\n - strange -> new\n - new -> life\nPath length: 4.0\nPath:\n - to -> seek\n - seek -> out\n - out -> new\n - new -> life\nPath length: 4.0\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    @Test
    public void testNoPath() {
        wordGraph.calcShortestPath("civilizations", "to","one_to_one");
        String expected = "No path found between civilizations and to\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    @Test
    public void testWord1NotInGraph() {
        wordGraph.calcShortestPath("apple", "to","one_to_one");
        String expected = "apple is not in the graph!\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    @Test
    public void testWord2NotInGraph() {
        wordGraph.calcShortestPath("to", "apple","one_to_one");
        String expected = "apple is not in the graph!\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    @Test
    public void testBothWordsNotInGraph() {
        wordGraph.calcShortestPath("banana", "apple","one_to_one");
        String expected = "Neither banana nor apple are in the graph!\n";
        assertEquals(normalize(expected), normalize(outContent.toString()));
    }

    private String normalize(String input) {
        return input.replaceAll("\\s+", " ").trim();
    }
}
